from http.server import HTTPServer, SimpleHTTPRequestHandler, HTTPStatus
from urllib import request

import config


def _load_http_address():
    '''从配置中读取服务地址
    '''
    address = config.SERVER_ADDRESS
    strings = address.split(':')

    host = strings[0]
    port = int(strings[1]) if len(strings) == 2 else 3000

    return (host, port)


def server():
    '''启动web服务器
    '''

    host, port = _load_http_address()
    print(f'Serving HTTP on {host} port {port}')

    httpd = HTTPServer((host, port), MyRequestHandler)
    httpd.serve_forever()


class MyRequestHandler(SimpleHTTPRequestHandler):
    '''请求处理器
    '''

    def log_request(self, code='-', size='-'):
        """Log an accepted request.

        This is called by send_response().

        """
        if isinstance(code, HTTPStatus):
            code = code.value

        # 中文解码
        self.log_message('"%s" %s %s',
                         request.unquote(self.requestline), str(code), str(size))
